package com.xykj.enterprise.wechat.ext.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xykj.enterprise.wechat.util.http.OkHttpUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.Map;

@Slf4j
public class QYWXHttpCommUtil {

    public static String domain = "https://qyapi.weixin.qq.com/cgi-bin/";

    public static <T> T postWithAccessToken(String fun, Map params, Class<T> clazz) {
        String json = OkHttpUtils.httpPostJson(buildPostAccessTokenUrl(fun, (String) params.get("access_token")), JSON.toJSONString(params));
        log.debug("请求原始报文:{}", json);
        return JSONObject.parseObject(json, clazz);
    }

    public static <T> T postWithAccessToken(String fun, String jsonParam, String access_token, Class<T> clazz) {
        String json = OkHttpUtils.httpPostJson(buildPostAccessTokenUrl(fun, access_token), jsonParam);
        log.debug("请求原始报文:{}", json);
        return JSONObject.parseObject(json, clazz);
    }

    public static <T> T postWithUrlParam(String fun, Map urlParams, Map params, Class<T> clazz) {
        String json = OkHttpUtils.httpPostJson(buildUrl(fun, urlParams), JSON.toJSONString(params));
        log.debug("请求原始报文:{}", json);
        return JSONObject.parseObject(json, clazz);
    }

    public static <T> T post(String fun, Map params, Class<T> clazz) {
        String json = OkHttpUtils.httpPostJson(buildUrl(fun, null), JSON.toJSONString(params));
        log.debug("请求原始报文:{}", json);
        return JSONObject.parseObject(json, clazz);
    }

    public static <T> T get(String fun, Map params, Class<T> clazz) {
        String json = OkHttpUtils.httpGet(buildUrl(fun, params));
        return JSONObject.parseObject(json, clazz);
    }

    private static String buildUrl(String function, Map params) {
        StringBuffer buffer = new StringBuffer();
        buffer.append(domain)
                .append(function);

        if (params == null || params.isEmpty()) {
            return buffer.toString();
        }
        buffer.append("?");
        Iterator<Map.Entry<Integer, Integer>> entries = params.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<Integer, Integer> entry = entries.next();
            buffer.append("&" + entry.getKey() + "=");
            buffer.append(entry.getValue());
        }
        return buffer.toString();
    }

    private static String buildPostAccessTokenUrl(String function, String accessToken) {
        StringBuffer buffer = new StringBuffer();
        buffer.append(domain)
                .append(function)
                .append("?1=1")
                .append("&access_token=")
                .append(accessToken)
        ;

        return buffer.toString();
    }


}
